package com.example.customview.view

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.view.View
import androidx.core.graphics.toColorInt
import com.example.customview.R
import com.sample.base.utils.dp
import java.io.File
import java.net.Socket
import kotlin.math.cos
import kotlin.math.sin

@SuppressLint("NewApi")
class DashboardView(context: Context?, attrs: AttributeSet?) : View(context, attrs) {

    companion object {
        val BOARD_RADIUS = 180f.dp
        val DASH_WIDTH = 6f.dp
        val DASH_LENGTH = 18f.dp
        val POINTER_LENGTH = 150f.dp
        const val OPEN_ANGLE = 120f

    }

    private val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
        color = Color.parseColor("#000000")
        style = Paint.Style.STROKE
        strokeWidth = 8.dp.toFloat()
//        strokeCap = Paint.Cap.ROUND

    }
    private val path = Path()
    private val dash = Path().apply {
        addRect(0f, 0f, DASH_WIDTH.toFloat(), DASH_LENGTH.toFloat(), Path.Direction.CCW)

    }

    private lateinit var pathEffect: PathEffect

    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        path.reset()
        path.addArc(
            width / 2f - BOARD_RADIUS,
            height / 2f - BOARD_RADIUS,
            width / 2f + BOARD_RADIUS,
            height / 2f + BOARD_RADIUS,
            90 + OPEN_ANGLE / 2f,
            360 - OPEN_ANGLE
        )
        // 用于测量 path 的路径
        val pathMeasure = PathMeasure(path, false)
        pathEffect = PathDashPathEffect(
            dash, (pathMeasure.length - DASH_WIDTH) / 20f, 0f,
            PathDashPathEffect.Style.ROTATE
        )
    }


    override fun onDraw(canvas: Canvas) {
        // 先画圆弧
        canvas.drawPath(path, paint)
        // 画刻度（其实也是画圆弧，只不过是用 dash 的方式来画）
        paint.pathEffect = pathEffect
        canvas.drawPath(path, paint)
        paint.pathEffect = null

        // 画指针
        paint.color = resources.getColor(R.color.colorJINLIANHUACHENG, resources.newTheme())
        paint.strokeWidth = 6.dp.toFloat()
        paint.strokeCap = Paint.Cap.ROUND
        val single = (360 - OPEN_ANGLE) / 20
        val mark = 12
        canvas.drawLine(
            width / 2f, height / 2f,
            (width / 2f + POINTER_LENGTH * cos(Math.toRadians((90 + OPEN_ANGLE / 2f + single * mark.toDouble()))).toFloat()),
            (height / 2f + POINTER_LENGTH * sin(Math.toRadians((90 + OPEN_ANGLE / 2f + single * mark.toDouble()))).toFloat()),
            paint
        )

    }
}